package com.lemon.components.ant.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import com.system.core.security.NameUtil;

public class DOMaker {

	public Connection getConnection(String url,String userName,String passwd){
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, userName, passwd);
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void make(String sql){
		String url = "jdbc:mysql://172.21.0.48:3306/testdinghaowu?useUnicode=true&allowMultiQueries=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull";
		Connection con = getConnection(url,"root","root");
		try {
			PreparedStatement p = con.prepareStatement(sql);
			ResultSet resultSet = p.executeQuery();
			ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
			int columns = resultSetMetaData.getColumnCount();
			
			StringBuilder sqlMapStr  = new StringBuilder("<resultMap id=\"\" type=\"\">\n");
			System.out.println("===================result object====================");
			for(int i=1 ;i<=columns;i++){
				String type = JdbcUtil.typeCoverJdbc2Java(resultSetMetaData.getColumnTypeName(i));
				String fieldName = NameUtil._2JavaName(resultSetMetaData.getColumnName(i));
				System.out.println("private "+type+" "+fieldName+";");
				sqlMapStr.append("\t<result column=\""+resultSetMetaData.getColumnName(i)+"\" jdbcType=\""+resultSetMetaData.getColumnTypeName(i)+"\" property=\""+fieldName+"\" />\n");
			}
			sqlMapStr.append("</resultMap>\n");
			System.out.println("===================resultmap xml====================");
			System.out.println(sqlMapStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		DOMaker doMaker = new DOMaker();
		String sql = "SELECT\r\n" + 
				"	dhw_operate_content.*\r\n" + 
				"FROM\r\n" + 
				"	dhw_operate_content\r\n" + 
				"LEFT JOIN dhw_operate_part ON dhw_operate_content.part_id = dhw_operate_part.part_id\r\n" + 
				"LEFT JOIN dhw_operate_modular ON dhw_operate_modular.mod_id = dhw_operate_part.mod_id\r\n" + 
				"WHERE\r\n" + 
				"	dhw_operate_modular.mod_id = 1\r\n" + 
				"AND dhw_operate_part.part_id = 1";
		doMaker.make(sql);
	}
}
